<template>
  <div class="dataset-list-container container-min-height">
    <div class="mb-24">
      <TopTabs @tab-click="handelTabClick" :tagsList="perTypeList">
        <div class="flex-between">
          <el-input
            v-model="searchValue"
            @input="handleDebounceSearch"
            placeholder="按名称搜索"
            prefix-icon="Search"
            class="w-240"
            style="max-width: 240px"
            clearable
          />
          <el-button
            type="primary"
            :icon="Plus"
            class="ml-12"
            @click="openCreateDialog"
          >
            创建新的知识库
          </el-button>
        </div>
      </TopTabs>
    </div>
    <InfiniteScroll
      :size="datasetList.length"
      :total="paginationConfig.total"
      :page_size="paginationConfig.page_size"
      v-model:current_page="paginationConfig.current_page"
      @load="getList"
      :loading="pageLoading"
    >
      <div
          v-loading="paginationConfig.current_page === 1 && pageLoading"
          element-loading-text="正在加载..."
          style="width: 100%"
          class="loading-page"
          v-if="pageLoading && !datasetList.length"
      ></div>
      <PageEmpty v-if="!datasetList.length && !pageLoading" :type="pageEmptyType"/>
      <el-row :gutter="15">
        <template v-for="(item, index) in datasetList" :key="index">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="mb-20">
            <CardBoxDataset
              :title="item.name"
              :description="item.description"
              :key="index"
              class="cursor"
              @click="router.push({ path: `/dataset/${item.maxId}/document` })"
            >
              <template #icon>
                <img  v-if="`${item.type}` === '1'" src="@/assets/dataset/icon_web.svg" style="width: 36" alt="" />
                <img  v-else  src="@/assets/dataset/icon_document.svg" style="width: 36" alt="" />
              </template>
              <!-- <template #subTitle>
                <el-text class="color-secondary" size="small">
                  <auto-tooltip :content="item.perUser">
                    创作者: {{ item.perUser }}
                  </auto-tooltip>
                </el-text>
              </template> -->
              <div class="delete-button">
                <el-tag
                  v-if="item.type === '0'"
                  style="height: 22px"
                  type="primary"
                >
                  通用型
                </el-tag>
                <el-tag
                  v-else-if="item.type === '1'"
                  type="warning"
                  style="height: 22px"
                  >web站点</el-tag
                >
              </div>

              <template #footer>
                <div class="footer-content flex-between">
                  <div class="flex-between text-ico">
                    <el-tooltip
                      effect="dark"
                      content="文档"
                      placement="top"
                    >
                      <SvgIcon iconClass="wds"></SvgIcon>
                    </el-tooltip>
                    <span>{{ item?.documentCount || 0 }}</span>

                    <el-divider direction="vertical" />
                    <el-tooltip
                      effect="dark"
                      content="字符"
                      placement="top"
                    >
                      <SvgIcon iconClass="zf"></SvgIcon>
                    </el-tooltip>
                    <span>{{ numberFormat(item?.charLength) || 0 }}</span>
                    <el-divider direction="vertical" />
                    <el-tooltip
                      effect="dark"
                      content="关联智能体"
                      placement="top"
                    >
                      <SvgIcon iconClass="glyy"></SvgIcon>
                    </el-tooltip>
                    <span>{{ item?.applicationMappingCount || 0 }}</span>
                  </div>
                  <div @click.stop>
                    <el-dropdown trigger="click">
                      <el-button text @click.stop>
                        <el-icon color="#8C8C8C "><MoreFilled /></el-icon>
                      </el-button>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item @click.stop="handelEdit(item)">
                            <SvgIcon iconClass="bianji" class="mr-5" style="font-size: 14px;"></SvgIcon>编辑
                          </el-dropdown-item>
                          <el-dropdown-item @click.stop="syncDataset(item)" v-if="`${item.type}` === '1'">
                            <SvgIcon iconClass="gengxin" class="mr-5" style="font-size: 14px;"></SvgIcon>更新
                          </el-dropdown-item>
                          <el-dropdown-item @click="reEmbeddingDataset(item)">
                            <AppIcon iconName="app-document-refresh" style="font-size: 16px"></AppIcon>向量化
                          </el-dropdown-item>
                          <el-dropdown-item icon="Setting" @click.stop="router.push({ path: `/dataset/${item.maxId}/setting` })" >设置 </el-dropdown-item>
                          <div class="export_zip_excel">
                            <el-dropdown-item @click.stop="export_dataset(item)">
                              <SvgIcon iconClass="daochu" class="mr-5" style="font-size: 14px;"></SvgIcon>导出 Excel
                            </el-dropdown-item>
                            <el-dropdown-item @click.stop="export_zip_dataset(item)">
                              <SvgIcon iconClass="daochuzip" class="mr-5" style="font-size: 14px;"></SvgIcon>导出 ZIP
                            </el-dropdown-item>
                          </div>
                          <el-dropdown-item icon="Delete" @click.stop="deleteDataset(item)">删除</el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </div>
                </div>
              </template>
            </CardBoxDataset>
          </el-col>
        </template>
      </el-row>
    </InfiniteScroll>
    <SyncWebDialog ref="SyncWebDialogRef" @refresh="refresh" />
    <CreateDatasetDialog ref="CreateDatasetDialogRef" @refresh="searchHandle"/>
    <EditDatasetDialog ref="EditDatasetDialogRef" @refresh="searchHandle"/>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted, reactive, h } from 'vue'
import SyncWebDialog from '@/views/dataset/component/SyncWebDialog.vue'
import CreateDatasetDialog from './component/CreateDatasetDialog.vue'
import EditDatasetDialog from './component/EditDatasetDialog.vue'
import datasetApi from '@/api/dataset'
import { MsgSuccess, MsgConfirm } from '@/utils/message'
import { useRouter } from 'vue-router'
import { numberFormat } from '@/utils/utils'
import useStore from '@/stores'
import { Plus } from '@element-plus/icons-vue'
import { pageDetail, delete2 } from '@/servers/ai/api/zhishiku'
import { Warning } from '@element-plus/icons-vue';
import { debounce } from 'lodash'

const { dataset } = useStore()
const router = useRouter()

const CreateDatasetDialogRef = ref()
const EditDatasetDialogRef = ref()
const SyncWebDialogRef = ref()
const pageLoading = ref(true)
const datasetList = ref<any[]>([])
const paginationConfig = reactive({
  current_page: 1,
  page_size: 10,
  total: 0
})
const searchValue = ref('')
const perTypeId = ref()
const perTypeList = ref()
const pageEmptyType = ref('4')
const handelTabClick = (item: any) => {
  perTypeId.value =  `${item.value === 'all' ? '' : item.value}`;
  searchHandle()
};

function openCreateDialog() {
  CreateDatasetDialogRef.value.open()
}

function refresh() {
  MsgSuccess('同步任务发送成功')
}

function reEmbeddingDataset(row: any) {
  datasetApi.putReEmbeddingDataset(row.maxId).then(() => {
    MsgSuccess('提交成功')
  })
}

function syncDataset(row: any) {
  SyncWebDialogRef.value.open(row.maxId)
}

const handleDebounceSearch = debounce(() => {
  searchHandle()
},500)
function searchHandle() {
  paginationConfig.current_page = 1
  paginationConfig.total = 0
  datasetList.value = []
  getList()
}
const export_dataset = (item: any) => {
  datasetApi.exportDataset(item.name, item.maxId, pageLoading).then((ok) => {
    MsgSuccess('导出成功')
  })
}
const export_zip_dataset = (item: any) => {
  datasetApi.exportZipDataset(item.name, item.maxId, pageLoading).then((ok) => {
    MsgSuccess('导出成功')
  })
}

function deleteDataset(row: any) {
  // 是否关联智能体
  const isRelated = row.applicationMappingCount ? true : false
  const text = isRelated
    ? ` 此知识库关联${row.applicationMappingCount}个智能体，删除后无法恢复，请谨慎操作。`
    : '删除后无法恢复，请谨慎操作。是否确认删除?';
  MsgConfirm(
    `提示`,
    text,
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      delete2([row.id]).then(() => {
        const index = datasetList.value.findIndex((v) => v.id === row.id)
        datasetList.value.splice(index, 1)
        MsgSuccess('删除成功')
      })
    })
    .catch(() => {})
}

function handelEdit(row: any) {
  EditDatasetDialogRef.value.open(row)
}

function getList() {
  const params = {
    "model": {
      "name": searchValue.value,  // 知识库名称
      "perType": perTypeId.value === 'all' ? '' : perTypeId.value, // perType
    },
    "size": paginationConfig.page_size,
    "current": paginationConfig.current_page,
  }
  if (searchValue.value.length) {
    pageEmptyType.value = '5'
  } else {
    pageEmptyType.value = '4'
  }
  pageLoading.value = true
  pageDetail(params).then((res: any) => {
    const { total, records } = res.data.data
    paginationConfig.total = Number(total);
    datasetList.value.push(...records)
  }).catch(() => {
      pageEmptyType.value = '3'
   }).finally(() => {
    pageLoading.value = false
  })
}

onMounted(async() => {
  // 获取分类
  const options: any = await dataset.getCategorizeOptions(true)
  perTypeList.value = [ {label: "全部", value: "all"}, ...options]
  perTypeId.value = 'all'

  // 获取列表
  getList()

})
</script>
<style lang="scss" scoped>
.dataset-list-container {
  .loading-page {
    position: absolute;
    top: 50%;
    margin-top: -18px;
  }
  .delete-button {
    position: absolute;
    right: 12px;
    top: 15px;
    height: auto;
  }
  .footer-content {
    .bold {
      color: var(--app-text-color);
    }
  }
  :deep(.el-divider__text) {
    background: var(--app-layout-bg-color);
  }
  .mb-20{
    margin-bottom: 20px;
  }
  .text-ico {
    span {
      padding-left: 5px;
    }
  }
}
.export_zip_excel{
  position: relative;
  padding-top: 12px;
  padding-bottom: 12px;
}
.export_zip_excel::before,
.export_zip_excel::after{
  position: absolute;
  content: '';
  background: #D9D9D9;
  width: 86px;
  height: 1px;
  left: 10px;
}
.export_zip_excel::after{
  top:6px;
}
.export_zip_excel::before{
 bottom:6px ;
}
</style>
